#!/bin/bash

echo "=== Debug Start ===" >&2
echo "User: $(whoami)" >&2
echo "PATH: $PATH" >&2
echo "Working Directory: $(pwd)" >&2
set -x  # 开启命令回显

# 设置工作目录
# 获取当前脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_DIR="$SCRIPT_DIR"
LOG_FILE=/dev/null #"$APP_DIR/taomu-platform.log"
PID_FILE="$APP_DIR/taomu-platform.pid"
JAVA_PATH="/usr/bin/java"  # 可通过 `which java` 查看路径

# 进入工作目录
cd "$APP_DIR" || exit 1

LOG4J_CONFIG="$APP_DIR/config/log4j.properties"
RUN_NAME="cool.taomu.toolkit.platform.Application"
MAIN_CLASS="cool.taomu.toolkit.platform.Application"
JAVA_OPTS=" -Dlog4j.configuration=file://$LOG4J_CONFIG -Dtaomu.profiles.active=pro "
JAVA_OPENS=" --add-opens java.base/java.time=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED "
CLASSPATH=.$CLASSPATH


function copy_if_exists() {
    local src="$1"
    local dest="$2"

    if [ -f "$src" ]; then
        cp "$src" "$dest"
        echo "Copied $src to $dest"
    else
        echo "Warning: $src does not exist. Skipping."
    fi
}


mkdir -p deps

SRC_DIR=".."
DEPS_DIR="./deps"

copy_if_exists "$SRC_DIR/taomu-platform-application/build/libs/taomu-platform-application-0.0.1-SNAPSHOT-all.jar" "$DEPS_DIR"
copy_if_exists "$SRC_DIR/taomu-stock/build/libs/taomu-stock-0.0.1-SNAPSHOT-all.jar" "$DEPS_DIR"

DIR=$(pwd)/deps/*.jar
for i in $DIR ;do
    CLASSPATH=$CLASSPATH:$i
done

#export JAVA_HOME=$JAVA_HOME

function start(){
	# 如果 PID 文件存在且进程还在运行，则退出
    if [ -f "$PID_FILE" ]; then
      if ps -p $(cat "$PID_FILE") > /dev/null; then
        echo "Application is already running."
        exit 1
      else
        rm -f "$PID_FILE"
      fi
    fi
    echo "$RUN_NAME trying to start ....."
    nohup $JAVA_PATH $JAVA_OPENS $JAVA_OPTS -cp $CLASSPATH $MAIN_CLASS >> $LOG_FILE 2>&1 &
    echo $! > $PID_FILE
    echo "$RUN_NAME started success. PID : $!"
}

function stop(){
    echo "Stopping $RUN_NAME ..."
    kill -9 `ps -ef|grep $RUN_NAME|grep -v grep|grep -v stop|awk '{print $2}'`
    rm "$PID_FILE"
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

echo "=== Debug End ===" >&2